/* 
* Copyright (C) 2005, 2006 Liu Di <liudidi@gmail.com> 
*
* Copyright (C) 2007 Wei Lian <lianwei3@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with this program; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "header.h"
#include "menubar.h"
#include "mainwindow.h"
#include "tabwidget.h"
#include "pageplay.h"
#include "mypopupmenu.h"
#include "config.h"
#include "playfork.h"
#include "channel.h"
#include "utils.h"
#include "record.h"


MenuBar::MenuBar (QWidget * parent, const char *name):
QMenuBar (parent, name),
mainwindow (static_cast < MainWindow * >(parent))
{
    ///initialization
    QSettings settings;
    ///
    int id = 0;
    ///menu file
    menu_file = new QPopupMenu (this);
    menu_file->insertItem (tr ("Exit"), qApp, SLOT (quit ()), CTRL + Key_Q, 0);
    insertItem (tr ("&File"), menu_file, id++);

    ///menu config
    menu_config = new QPopupMenu (this);
    menu_config->setCheckable (true);
    //channel color
    submenu_color = new QPopupMenu (this);
    submenu_color->setCheckable (true);
    submenu_color->insertItem (tr ("User"), USER_COLUMN);
    submenu_color->insertItem (tr ("Visit"), VISIT_COLUMN);
    submenu_color->insertItem (tr ("Qs"), QS_COLUMN);
    submenu_color->insertItem (tr ("Qc"), QC_COLUMN);
    submenu_color->insertItem (tr ("Kbps"), KBPS_COLUMN);
    color_column = settings.readNumEntry ("/qsopcast/ChannelColor", USER_COLUMN);
    submenu_color->setItemChecked (color_column, true);
    connect (submenu_color, SIGNAL (activated (int)), this, SLOT (onSwitchColor (int)));
    menu_config->insertItem (tr ("Channel Color"), submenu_color, CHANNEL_COLOR);
    //show null channel
    menu_config->insertItem (tr ("&Show Null Channel"), this,
			     SLOT (onNullChannelToggled ()), CTRL + Key_N, NULL_CHANNEL);
    menu_config->setItemChecked (NULL_CHANNEL,
				 settings.readBoolEntry ("/qsopcast/shownullchannels", FALSE));
    //enabel channel sorting
    menu_config->insertItem (tr ("&Enable Channel Sorting"), this,
			     SLOT (onChannelSortToggled ()), CTRL + Key_S, CHANNEL_SORT);
    menu_config->setItemChecked (CHANNEL_SORT,
				 settings.readBoolEntry ("/qsopcast/enablechannelsorting", FALSE));
    //enable auto restart player
    menu_config->insertItem (tr ("&Enable Auto Restarting Player"), this,
			     SLOT (onAutoRestartPlayerToggled ()),
			     CTRL + Key_P, AUTO_RESTART_PLAYER);
    menu_config->setItemChecked (AUTO_RESTART_PLAYER,
				 settings.
				 readBoolEntry ("/qsopcast/enableautorestartplayer", FALSE));
    //configuration
    menu_config->insertItem (tr ("&Config"), this, SLOT (onconfigclicked ()),
			     CTRL + Key_F, CONFIG);
    insertItem (tr ("&Config"), menu_config, id++);

    ///menu history
    history = new QPopupMenu (this);
    history->insertItem (tr ("&Clear"), this, SLOT (clearHistory ()), CTRL + Key_K, 0);
    history->insertSeparator ();
    connect (history, SIGNAL (activated (int)), this, SLOT (onChooseHistory (int)));
    insertItem (tr ("&History"), history, id++);

    ///menu bookmark
    bookmark = new MyPopupMenu (this);
    bookmark->insertItem (tr ("&Add"), this, SLOT (addToBookmark ()), CTRL + Key_B, 0);
    bookmark->insertSeparator ();
    connect (bookmark, SIGNAL (activated (int)), this, SLOT (onChooseBookmark (int)));
    insertItem (tr ("&Bookmark"), bookmark, id++);

    ///menu help
    menu_help = new QPopupMenu (this);
    menu_help->insertItem (tr ("&About"), this, SLOT (about ()), CTRL + Key_H, 0);
    insertItem (tr ("&Help"), menu_help, id++);

}


MenuBar::~MenuBar ()
{
    QSettings settings;
    settings.writeEntry ("/qsopcast/ChannelColor", color_column);
    settings.writeEntry ("/qsopcast/shownullchannels", menu_config->isItemChecked (NULL_CHANNEL));
    settings.writeEntry ("/qsopcast/enablechannelsorting",
			 menu_config->isItemChecked (CHANNEL_SORT));
    settings.writeEntry ("/qsopcast/enableautorestartplayer",
			 menu_config->isItemChecked (AUTO_RESTART_PLAYER));

}


void
MenuBar::clearHistory ()
{
    for (int index = history->count () - 1; index >= 2; index--) {
	history->removeItemAt (index);
    }
}

void
MenuBar::onSwitchColor (int id)
{
    mainwindow->channel->switchChannelColor (id);
    color_column = id;
    for (uint index = 0; index < submenu_color->count (); index++)
	submenu_color->setItemChecked (submenu_color->idAt (index), false);
    submenu_color->setItemChecked (id, true);
}


void
MenuBar::onChannelSortToggled ()
{
    menu_config->setItemChecked (CHANNEL_SORT, !menu_config->isItemChecked (CHANNEL_SORT));
    mainwindow->channel->toggleChannelSort ();
}


void
MenuBar::onNullChannelToggled ()
{
    menu_config->setItemChecked (NULL_CHANNEL, !menu_config->isItemChecked (NULL_CHANNEL));
    mainwindow->channel->toggleNullChannel ();
}


void
MenuBar::onAutoRestartPlayerToggled ()
{
    menu_config->setItemChecked (AUTO_RESTART_PLAYER,
				 !menu_config->isItemChecked (AUTO_RESTART_PLAYER));
}


void
MenuBar::onconfigclicked ()
{
    mainwindow->vboxconfig->
	move (mapToGlobal
	      (QPoint
	       ((mainwindow->width () - mainwindow->vboxconfig->width ()) / 2,
		(mainwindow->height () - mainwindow->vboxconfig->height ()) / 2)));
    mainwindow->vboxconfig->show ();

}


void
MenuBar::onChooseHistory (int id)
{
//    printf("history index=%d,id=%d\n", history->indexOf(id), id);
    if (id < 2)
	return;

    ///get name, url and type of channel
    QString str = history->text (id);
    QString name = str.mid (0,
			    str.find (mainwindow->vboxconfig->editchannelheader->text ()) - 1);
    QString url = str.mid (str.find (mainwindow->vboxconfig->editchannelheader->text ()));
    QString type = url.mid (url.find (" ") + 1);
    url = url.mid (0, url.find (" "));

    ///play or record 
    if (static_cast < MyHBox * >(mainwindow->tabwidget->currentPage ())
	->pagetype == "play") {
	PagePlay *page = static_cast < PagePlay * >(mainwindow->tabwidget->currentPage ());
	page->channelname = name;
	page->channelurl = url;
	page->channeltype = type;
	page->flagMenu = true;
	page->onButtonLaunchClicked ();
	page->flagMenu = false;
    } else {
	Record *page = static_cast < Record * >(mainwindow->tabwidget->currentPage ());
	if (!page->buttonrecord->isOn ()) {
	    page->channelname = name;
	    page->channelurl = url;
	    page->channeltype = type;
	    page->flagMenu = true;
	    page->buttonrecord->setOn (true);
	    page->flagMenu = false;
	}
    }
}


void
MenuBar::onChooseBookmark (int id)
{
//    printf("bookmark index=%d,id=%d\n", bookmark->indexOf(id), id);
    if (id < 2)
	return;

    if (bookmark->rightbutton) {	///delete bookmark
	bookmark->removeItem (id);
    } else {
	///get name, url and type of channel
	QString str = bookmark->text (id);
	QString name = str.mid (0,
				str.find (mainwindow->vboxconfig->editchannelheader->text ()) - 1);
	QString url = str.mid (str.find (mainwindow->vboxconfig->editchannelheader->text ()));
	QString type = url.mid (url.find (" ") + 1);
	url = url.mid (0, url.find (" "));

	///play or record        
	if (static_cast < MyHBox * >(mainwindow->tabwidget->currentPage ())
	    ->pagetype == "play") {
	    PagePlay *page = static_cast < PagePlay * >(mainwindow->tabwidget->currentPage ());
	    page->channelname = name;
	    page->channelurl = url;
	    page->channeltype = type;
	    page->flagMenu = true;
	    page->onButtonLaunchClicked ();
	    page->flagMenu = false;
	} else {
	    Record *page = static_cast < Record * >(mainwindow->tabwidget->currentPage ());
	    if (!page->buttonrecord->isOn ()) {
		page->channelname = name;
		page->channelurl = url;
		page->channeltype = type;
		page->flagMenu = true;
		page->buttonrecord->setOn (true);
		page->flagMenu = false;
	    }
	}
    }
}


void
MenuBar::addToPopupMenu (QPopupMenu * menu, QString url, QString name, QString type)
{
    if (menu->count () == 2)	///no item
	menu->insertItem (name + " " + url + " " + type, 2);
    else if (menu->count () > 2) {
	bool flag = FALSE;
	uint index;
	for (index = 2; index < menu->count (); index++) {
	    QString str = menu->text (menu->idAt (index));
	    QString str_name = str.mid (0,
					str.find (mainwindow->vboxconfig->
						  editchannelheader->text ()) - 1);
	    QString str_url =
		str.mid (str.find (mainwindow->vboxconfig->editchannelheader->text ()));
	    QString str_type = str_url.mid (str_url.find (" ") + 1);
	    str_url = str_url.mid (0, str_url.find (" "));

	    if (url == str_url) {
		if (name != str_name || type != str_type) {
		    menu->changeItem (menu->idAt (index), name + " " + url + " " + type);
		}
		flag = TRUE;
		break;
	    }
	}
	if (flag == FALSE)
	    menu->insertItem (name + " " + url + " " + type, menu->idAt (index - 1) + 1);
    } else
	fprintf (stderr, "err: count<2\n");
}


void
MenuBar::addToBookmark ()
{
    QString channelurl, channelname, channeltype;

    channelurl = mainwindow->editsearch->text ();
    ///editsearch has focus and contains a valid Sop URL
    if (mainwindow->editsearch->hasFocus () &&
	mainwindow->channel->SopMatch (channelurl, channelname, channeltype)) {
    } else {
	///editsearch has no focus
	QListViewItem *item = mainwindow->channel->currentItem ();
	if (item == 0 || item->depth () != 1)
	    return;
	channelurl = item->text (URL_COLUMN);
	channelname = item->text (NAME_COLUMN);
	channeltype = item->text (STREAM_COLUMN);
    }
    addToPopupMenu (bookmark, channelurl, channelname, channeltype);
}


#include "icons/mozart.xpm"
void
MenuBar::about ()
{
    const QPixmap p1 (mozart);
    QMessageBox m;
    m.setCaption ("qsopcast");
    m.setIconPixmap (p1);
    m.setText (tr ("qsopcast: a QT front-end to p2p TV sopcast.\n"
		   "Copyright (C) 2005, 2006 Liu Di, 2007 Wei Lian.\n"
		   "Maintainer: Wei Lian\n"
		   "Developers: Liu Di, Wei Lian\n" "http://code.google.com/p/qsopcast/"));
    m.exec ();
}
